package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //解决跨域访问时的拦截bug
        if(!( handler instanceof HandlerMethod)){
                return true;
        }
        //细节,放方法前面,不是访问要登入的方法也会延长30秒
        String token = request.getHeader("token");
        UserInfo userInfo = userInfoRedisService.getToken(token);
        //1识别请求方法 是否有@RequireLogin标签
        HandlerMethod method = (HandlerMethod) handler;
        if(method.hasMethodAnnotation(RequireLogin.class)){
            //2如果贴了就要登入拦截
            if (userInfo == null){
                //响应给浏览器没登入的信息
                response.setContentType("appliction/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        //3没有贴,就放行
        return true;

    }
}
